package com.baidu.cleaner.checker;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class DateChecker implements Checker {
	// YYYY-MM-DD
	private static final String f1 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
	// YYYYMMDD
	private static final String f2 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)";

	private boolean isNull = false;

	private String format = null;

	public boolean getIsNull() {
		return isNull;
	}

	public void setIsNull(boolean isNull) {
		this.isNull = isNull;
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	@Override
	public boolean verify(String value) throws Exception {
		if (!isNull && StringUtils.isBlank(value)) {
			throw new Exception("the value can not be empty");
		} else if (isNull && StringUtils.isBlank(value)) {
			return true;
		} else {
			if (StringUtils.equalsIgnoreCase(format, "YYYYMMDD") && StringUtils.equalsIgnoreCase(format, "YYYY-MM-DD")) {
				throw new Exception("unknow format:" + this.format);
			} else if (StringUtils.equalsIgnoreCase(format, "YYYY-MM-DD") && !Pattern.matches(f1, value)) {
				throw new Exception("the value is not match with YYYY-MM-DD");
			} else if (StringUtils.equalsIgnoreCase(format, "YYYYMMDD") && !Pattern.matches(f2, value)) {
				throw new Exception("the value is not match with YYYYMMDD");
			} else {
				return true;
			}
		}
	}

	public static void main(String[] args) throws Exception {
		DateChecker dc = new DateChecker();
		dc.setFormat("yyyy-mm-dd");
		System.out.println(dc.verify("2012-09-31"));
	}
}
